package com.yiv.yivbackend.service.impl;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yiv.yivbackend.model.domain.User;
import com.yiv.yivbackend.service.UserService;
import com.yiv.yivbackend.mapper.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @author 48852
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-10-29 17:44:48
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    
    @Resource
    private UserMapper userMapper;




    /**
     * 加密用的 “盐值”
     */
    @Resource
    private static final String SALT = "Yivi";


    /**
     * 用户登录唯一的键（唯一的key）---> 找到唯一的值
     */
    @Resource
    private static final String USER_LOGIN_STATE = "user_login_state";

    /**
     * 用户注册
     *
     * @param userAccount   用户账户
     * @param userPassword  账户密码
     * @param checkPassword 校验码
     * @return user id
     */
    @Override
    public long userRegistration(String userAccount, String userPassword, String checkPassword){
//        校验
//        判断前端传来的数据非空（用commons-lang自带库）
        if(StringUtils.isAnyBlank(userAccount,userPassword,checkPassword)){
            return -1;
        }

//        账户长度不小于4位
        if (userAccount.length()<4){
            return -1;
        }

//        密码长度不小于8位
        if (userPassword.length()<8 || checkPassword.length()<8){
            return -1;
        }

//        账户不能包含特殊字符
        String validpattern = "^[a-zA-Z0-9_-]+$";
        Matcher matcher = Pattern.compile(validpattern).matcher(userAccount);
        if(!matcher.find()){
            return -1;
        }

//         密码校验码要相同
        if(!userPassword.equals(checkPassword)){
            return -1;
        }

//        账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        Long count= userMapper.selectCount(queryWrapper);
        if(count>0){
            return -1;
        }

//       加密
//       对密码加密
        String encrptPassword = DigestUtils.md5DigestAsHex((SALT+ "userPassword").getBytes());

//       向数据库插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encrptPassword);
        boolean saveResult = this.save(user);
        if(!saveResult){
            return -1;
        }
        return user.getId();
    }

    /**
     * 用户登录
     *
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @return 脱敏后的用户信息
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
//        校验用户账户和密码是否合法
//        判断前端传来的数据非空（用commons-lang自带库）
        if(StringUtils.isAnyBlank(userAccount,userPassword)){
            return null;
        }

//        账户长度不小于4位
        if (userAccount.length()<4){
            return null;
        }

//        密码长度不小于8位
        if (userPassword.length()<8){
            return null;
        }

//        账户不能包含特殊字符
        String validpattern = "^[a-zA-Z0-9_-]+$";
        Matcher matcher = Pattern.compile(validpattern).matcher(userAccount);
        if(!matcher.find()){
            return null;
        }

//       校验密码
//       对密码加密
        String encrptPassword = DigestUtils.md5DigestAsHex((SALT+ "password").getBytes());
//       查数据库(数据库删除状态 0-未删除)
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        queryWrapper.eq("userPassword",encrptPassword);
        User user = userMapper.selectOne(queryWrapper);
//        判断用户不存在
        if(user==null){
            //  日志记录
            log.info("user not exist or password not correct");
            return null;
        }

//      用户信息脱敏
        User saftyUser = new User();
        saftyUser.setId(saftyUser.getId());
        saftyUser.setUsername(saftyUser.getUsername());
        saftyUser.setAvatarUrl(saftyUser.getAvatarUrl());
        saftyUser.setUserAccount(saftyUser.getUserAccount());
        saftyUser.setGender(saftyUser.getGender());
        saftyUser.setPhone(saftyUser.getPhone());
        saftyUser.setEmail(saftyUser.getEmail());
        saftyUser.setUserStatus(saftyUser.getUserStatus());
        saftyUser.setCreateTime(saftyUser.getCreateTime());


//        记录用户登录态(通过session)
        request.getSession().setAttribute(USER_LOGIN_STATE, saftyUser);


//        返回脱敏后的用户信息
        return saftyUser;
    }
}




